/**
Company: Sarkar software technologys
WebSite: http://www.sarkar.cn
Author: yeganaaa
Date : 7/3/18
Time: 9:21 AM
 */

package Cn.Sarkar.MMS.LayerOne.Repositories.RDBMSRepositories

import Cn.Sarkar.Entities.Common.Additional.IDescription
import Cn.Sarkar.Entities.Common.Additional.IName
import Cn.Sarkar.EntityDream.CoreEngine.RDBMS.Core.QueryBuilderExtensions.SelectQueryExpression.and
import Cn.Sarkar.EntityDream.CoreEngine.RDBMS.Core.QueryBuilderExtensions.SelectQueryExpression.equals
import Cn.Sarkar.EntityDream.CoreEngine.RDBMS.Core.QueryBuilderExtensions.SelectQueryExpression.singleOrNull
import Cn.Sarkar.MMS.DataBaseDefinations.Additional.Descriptions
import Cn.Sarkar.MMS.Entities.Additional.Description
import Cn.Sarkar.MMS.Entities.DataSources.IDataSource
import Cn.Sarkar.MMS.LayerOne.Repositories.Interfaces.IDescriptionRepository
import Cn.Sarkar.MMS.LayerOne.Repositories.Interfaces.RepositoryResult
import Cn.Sarkar.MMS.LayerOne.Repositories.Interfaces.tryExecute

class DescriptionRepository : IDescriptionRepository, IRDBMSRepositories {
    override fun getOrStore(_description: IDescription): RepositoryResult<IDescription?> = tryExecute {
        IDataSource.openAndAutoClose {db ->
            var description = db.descriptions.singleOrNull {
                Descriptions.Category equals _description.category and
                        (Descriptions.Ug equals _description.ug) and
                        (Descriptions.En equals _description.en) and
                        (Descriptions.Zh equals _description.zh) and
                        (Descriptions.Kz equals _description.kz) and
                        (Descriptions.Ru equals _description.ru)

            }
            if (description == null) {
                description = Description(db).apply {
                    category = _description.category
                    ug = _description.ug
                    en = _description.en
                    zh = _description.zh
                    kz = _description.kz
                    ru = _description.ru
                }
                db.descriptions.add(description)
                db.saveChanges()
            }
            description
        }
    }
}
